package uit.qlks.from;

import java.awt.event.KeyEvent;
import java.math.BigInteger;
import java.rmi.Naming;
import java.security.MessageDigest;
import javax.sql.rowset.WebRowSet;
import javax.swing.*;
import uit.ejb.dto.UserDTO;
import uit.qlks.controller.user.UserController;

public class frmNguoidung extends javax.swing.JFrame {

    private static frmQuanlynguoidung _frm;
    private static int _i;
    private String passtemp = "";

    public frmNguoidung(frmQuanlynguoidung frm, int i) {
        initComponents();
        _frm = frm;
        _i = i;
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        txtTennguoidung = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtTaikhoan = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        rbtnQuantri = new javax.swing.JRadioButton();
        rbtnNhanvien = new javax.swing.JRadioButton();
        btnDangky = new javax.swing.JButton();
        txtMatKhau2 = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cập Nhật Tài Khoản");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });
        getContentPane().setLayout(null);

        txtTennguoidung.setFont(new java.awt.Font("Times New Roman", 0, 18));
        txtTennguoidung.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTennguoidungKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTennguoidungKeyTyped(evt);
            }
        });
        getContentPane().add(txtTennguoidung);
        txtTennguoidung.setBounds(150, 30, 250, 28);

        jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel2.setText("Tên người dùng:");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(20, 30, 119, 22);

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel3.setText("Tài khoản:");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(20, 80, 128, 22);

        txtTaikhoan.setFont(new java.awt.Font("Times New Roman", 0, 18));
        txtTaikhoan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTennguoidungKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTaikhoanKeyTyped(evt);
            }
        });
        getContentPane().add(txtTaikhoan);
        txtTaikhoan.setBounds(150, 80, 250, 28);

        jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel4.setText("Quyền:");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(30, 170, 80, 22);

        jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel5.setText("Mật khẩu:");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(30, 130, 128, 22);

        buttonGroup1.add(rbtnQuantri);
        rbtnQuantri.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        rbtnQuantri.setText("Quản trị");
        getContentPane().add(rbtnQuantri);
        rbtnQuantri.setBounds(290, 170, 100, 31);

        buttonGroup1.add(rbtnNhanvien);
        rbtnNhanvien.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        rbtnNhanvien.setText("Nhân viên");
        getContentPane().add(rbtnNhanvien);
        rbtnNhanvien.setBounds(160, 170, 99, 31);

        btnDangky.setFont(new java.awt.Font("Times New Roman", 0, 16));
        btnDangky.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Edit.png"))); // NOI18N
        btnDangky.setText("Đăng kí");
        btnDangky.setBorder(null);
        btnDangky.setContentAreaFilled(false);
        btnDangky.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Edit2.png"))); // NOI18N
        btnDangky.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDangkyActionPerformed(evt);
            }
        });
        getContentPane().add(btnDangky);
        btnDangky.setBounds(180, 220, 90, 30);

        txtMatKhau2.setFont(new java.awt.Font("Times New Roman", 0, 16));
        txtMatKhau2.setName("txtMatKhau"); // NOI18N
        txtMatKhau2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTennguoidungKeyPressed(evt);
            }
        });
        getContentPane().add(txtMatKhau2);
        txtMatKhau2.setBounds(150, 125, 180, 30);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-450)/2, (screenSize.height-300)/2, 450, 300);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        _frm.setVisible(true);
        _frm.setFocusable(true);
    }//GEN-LAST:event_formWindowClosed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add you
        if (_i == 1) {
            txtTennguoidung.setText(_frm._us.getFullName());
            txtTaikhoan.setText(_frm._us.getUserName());
//            char[] pass=_frm._us.Password.toCharArray();
//            txtMatkhau.setText(String.valueOf(pass));
            passtemp = _frm._us.getPassword();
            txtMatKhau2.setText("!!!!!!!!");
            if (Integer.parseInt(_frm._us.getRole()) == 1) {
                rbtnNhanvien.setSelected(true);
            } else {
                rbtnQuantri.setSelected(true);
            }
            btnDangky.setText("Cập nhật");
        }
        if (Integer.parseInt(frmLogin._us.getRole()) <= 1) {
            rbtnNhanvien.setSelected(true);
            rbtnNhanvien.setEnabled(false);
            rbtnQuantri.setEnabled(false);
        }
    }//GEN-LAST:event_formComponentShown

    private void txtTennguoidungKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTennguoidungKeyTyped
        // TODO add your handling code here:
        if (txtTennguoidung.getText().length() == 50) {
            getToolkit().beep();
            evt.consume();
        }
    }//GEN-LAST:event_txtTennguoidungKeyTyped

    private void txtTaikhoanKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTaikhoanKeyTyped
        // TODO add your handling code here:
        if (txtTaikhoan.getText().length() == 20) {
            getToolkit().beep();
            evt.consume();
        }
        if (!Character.isLetterOrDigit(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar())) {
            getToolkit().beep();
            evt.consume();
        }
    }//GEN-LAST:event_txtTaikhoanKeyTyped

    private void dangKy() {
        try {
            if (_i == 0) {
                if (btnDangky.getText().equals("Đăng kí")) {
                    if (KiemTraDuLieu() == 0) {
                        return;
                    }
                    UserDTO us = new UserDTO();
                    us.setFullName(txtTennguoidung.getText());
                    us.setPassword(encryptMD5(txtMatKhau2.getText()));
                    us.setUserName(txtTaikhoan.getText());
                    if (rbtnNhanvien.isSelected()) {
                        us.setRole("1");
                    } else {
                        us.setRole("2");
                    }
                    WebRowSet wrs = UserController.user_GetById(us);
                    if (wrs.next()) {
                        JOptionPane.showMessageDialog(this, "Tài khoản đã tồn tài ", "Thông báo", JOptionPane.ERROR_MESSAGE);
                        txtTaikhoan.setFocusable(true);
                        return;
                    }
                    UserController.user_Insert(us);
                    JOptionPane.showMessageDialog(this, "Thêm người dùng thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                }
            } else {
                int result = JOptionPane.showConfirmDialog(this, "Bạn chắc chắn muốn cập nhật thông tin?", "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (result == JOptionPane.YES_OPTION) {
                    if (KiemTraDuLieu() == 0) {
                        return;
                    }
                    UserDTO us = new UserDTO();
                    us.setFullName(txtTennguoidung.getText());
                    if ("!!!!!!!!".equals(txtMatKhau2.getText())) {
                        us.setPassword(passtemp);
                    } else {
                        us.setPassword(encryptMD5(txtMatKhau2.getText()));
                    }
                    us.setUserName((txtTaikhoan.getText()));
                    if (rbtnNhanvien.isSelected()) {
                        us.setRole("1");
                    } else {
                        us.setRole("2");
                    }
                    WebRowSet wrs = UserController.user_GetById(us);
                    if (wrs.next()) {
                        us.setId(wrs.getObject("Id").toString());
                        if (Integer.parseInt(us.getId()) != Integer.parseInt(_frm._us.getId())) {
                            JOptionPane.showMessageDialog(this, "Tài khoản đã tồn tài ", "Thông báo", JOptionPane.ERROR_MESSAGE);
                            txtTaikhoan.setFocusable(true);
                            return;
                        }
                    }
                    us.setId(_frm._us.getId());
                    UserController.user_Update(us);
                    if (us.getUserName().equals(frmLogin._us.getUserName())) {
                        frmLogin._us.setUserName(us.getUserName());
                        frmLogin._us.setRole(us.getRole());
                    }
                    JOptionPane.showMessageDialog(this, "Cập nhật người dùng thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }
    private void btnDangkyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDangkyActionPerformed

        dangKy();
    }//GEN-LAST:event_btnDangkyActionPerformed

private void txtTennguoidungKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTennguoidungKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        dangKy();
    }
    // TODO add your handling code here:
}//GEN-LAST:event_txtTennguoidungKeyPressed
    public static String encryptMD5(String code) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(code.getBytes());
            BigInteger dis = new BigInteger(1, md5.digest());
            code = dis.toString(16);
            return code;
        } catch (Exception e) {

            return code;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmNguoidung(_frm, _i).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDangky;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JRadioButton rbtnNhanvien;
    private javax.swing.JRadioButton rbtnQuantri;
    private javax.swing.JPasswordField txtMatKhau2;
    private javax.swing.JTextField txtTaikhoan;
    private javax.swing.JTextField txtTennguoidung;
    // End of variables declaration//GEN-END:variables

    private int KiemTraDuLieu() {
        if (txtTennguoidung.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập tên người dùng", "Thông báo", JOptionPane.ERROR_MESSAGE);
            txtTennguoidung.requestFocusInWindow();
            return 0;
        }
        if (txtTaikhoan.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập tài khoản", "Thông báo", JOptionPane.ERROR_MESSAGE);
            txtTaikhoan.requestFocusInWindow();
            return 0;

        }
        if (txtMatKhau2.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập mật khẩu", "Thông báo", JOptionPane.ERROR_MESSAGE);
            txtMatKhau2.requestFocusInWindow();
            return 0;
        }

        if (rbtnNhanvien.isSelected() == false && rbtnQuantri.isSelected() == false) {
            JOptionPane.showMessageDialog(this, "Bạn chưa chọn quyền người dùng", "Thông báo", JOptionPane.ERROR_MESSAGE);
            return 0;

        }
        if (txtMatKhau2.getText().length() < 3) {
            JOptionPane.showMessageDialog(this, "Mật khẩu phải hơn 5 kí tự", "Thông báo", JOptionPane.ERROR_MESSAGE);
            txtMatKhau2.setFocusable(true);
            return 0;
        }
        return 1;
    }
}
